window.onload = function() {
    const itemBox = document.getElementsByClassName('item-box')[0] //获取父盒子
    itemBox.addEventListener('click', boxAnimation, false) //冒泡监听，事件代理

    function boxAnimation(event) { //可以对函数进行节流或者防抖，防止用户点击过快（动画有延时时间）
        const rootSize = parseFloat(window.getComputedStyle(document.documentElement).fontSize) //获取到字体的相对大小
        const itemAtt = document.getElementById('item-att') //滑块 
        const target = event && event.target || boxAnimation.startTarget //目标元素，设定初始目标元素
        if (target.tagName.toLowerCase() === 'li') { //判断条件
            boxAnimation.current = target
            const parent = target.parentElement
            const parentRect = parent.getBoundingClientRect()
            const Rect = target.getBoundingClientRect()
            boxAnimation.last && (boxAnimation.last.style.color = '#000')
            target.style.color = '#fff'
            itemAtt.style.cssText = `
                width: ${Rect.width}px;
                height: ${Rect.height}px;
                left: ${(Rect.left - parentRect.left)}px;
            `
            boxAnimation.last = target
        }
    }
    boxAnimation.startTarget = itemBox.children[0] //设置初始元素
    boxAnimation() //先调用一次，保证滑块位置和大小

    //使用防抖控制性能
    window.addEventListener('resize', debounce(function(e) {
        boxAnimation.startTarget = boxAnimation.last
        boxAnimation()
    }, 60))

    //防抖函数
    function debounce(callback, spaceTime) {
        let timer = null
        return function(...args) {
            if (timer) clearTimeout(timer)
            timer = setTimeout(() => {
                callback.apply(this, args)
            }, spaceTime);
        }
    }
}